import { getGoods } from "@/api/goods";

const state = {
  goodsList: [],
};

const mutations = {
  SET_GOODS_LIST(state, list) {
    state.goodsList = list;
    localStorage.setItem("vuex-goods", JSON.stringify(list));
  },
  // 保持原有UPDATE_CART_ITEM不变
  UPDATE_CART_ITEM(state, { productId, quantity, totalPrice }) {
    const productIndex = state.goodsList.findIndex(
      (product) => product.product_id === productId
    );
    if (productIndex !== -1) {
      state.goodsList[productIndex].number = quantity;
    }
    state.goodsList.totalPrice = totalPrice;
    console.log(state.goodsList);
    localStorage.setItem("vuex-goods", JSON.stringify(state.goodsList));
  },
  // 修正新增商品方法
  ADD_PRODUCT(state, product) {
    const exists = state.goodsList.some(
      (p) => p.product_id === product.product_id
    );
    if (!exists) {
      state.goodsList.push({
        ...product,
        number: product.number || 0,
        totalPrice: product.price * (product.number || 0),
      });
      localStorage.setItem("vuex-goods", JSON.stringify(state.goodsList));
    }
  },
  // 修正更新商品方法
  UPDATE_PRODUCT(state, updatedProduct) {
    const index = state.goodsList.findIndex(
      (p) => p.product_id === updatedProduct.product_id
    );
    if (index !== -1) {
      state.goodsList.splice(index, 1, {
        ...state.goodsList[index],
        ...updatedProduct,
        totalPrice: updatedProduct.price * (updatedProduct.number || 0),
      });
      localStorage.setItem("vuex-goods", JSON.stringify(state.goodsList));
    }
  },
  // 保持删除方法不变
  DELETE_PRODUCT(state, productId) {
    state.goodsList = state.goodsList.filter((p) => p.product_id !== productId);
    localStorage.setItem("vuex-goods", JSON.stringify(state.goodsList));
  },
};

const actions = {
  async getGoodsList({ commit }) {
    const localData = localStorage.getItem("vuex-goods");
    if (localData) {
      commit("SET_GOODS_LIST", JSON.parse(localData));
      return;
    }
    const response = await getGoods();
    commit("SET_GOODS_LIST", response.data);
  },
  addProduct({ commit }, product) {
    commit("ADD_PRODUCT", product);
  },
  updateProduct({ commit }, product) {
    commit("UPDATE_PRODUCT", product);
  },
  deleteProduct({ commit }, productId) {
    commit("DELETE_PRODUCT", productId);
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
